package com.srwl.mytx.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.ViewUtils;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.srwl.mytx.R;
import com.srwl.mytx.adapter.ConversationListAdapter;
import com.srwl.mytx.adapter.MenuArrayAdapter;
import com.srwl.mytx.domain.ConversationData;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.im.ConversationListener;
import com.srwl.mytx.im.ConversationService;
import com.srwl.mytx.utils.Utils;

import java.util.ArrayList;
import java.util.List;

public class ConversationListView extends RecyclerView implements ConversationListAdapter.InteractionListener, ConversationListener {

    private static final String TAG = "ConversationListView";
    private Context context;
    private List<Conversation> conversationList = new ArrayList<>();
    private ConversationListAdapter conversationListAdapter;
    protected ConversationService conversationService;
    private MotionEvent touchEvent;

    public ConversationListView(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    public ConversationListView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public ConversationListView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
    }

    public void init(ConversationService conversationService) {
        if (conversationService == null) {
            return;
        }
        //避免重复初始化
//        if (this.conversationService != null) {
//            return;
//        }
        this.conversationService = conversationService;
        conversationList.clear();
        conversationList.addAll(loadConversationList());
        setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
        conversationListAdapter = new ConversationListAdapter(context, conversationList, this);
        setAdapter(conversationListAdapter);
        //ItemTouchHelper touchHelper = new ItemTouchHelper(new MyItemTouchHelperCallBack());//很容易造成误触 为删除会话
        //touchHelper.attachToRecyclerView(this);
        conversationService.setConversationListener(this);
    }

    public void filter(CharSequence str) {
        conversationListAdapter.filter(str);
    }

    public void clearFilter() {
        conversationListAdapter.clearFilter();
    }

    public void refresh() {
        conversationList.clear();
        conversationList.addAll(loadConversationList());
        //游客状态 适配器是空的，需要判断
        if (conversationListAdapter != null) {
            conversationListAdapter.notifyDataSetChanged();
        }
    }

    protected List<Conversation> loadConversationList() {

        if (conversationService == null) {
            return new ArrayList<>();
        }
        return conversationService.getConversationList();
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            touchEvent = event;
        }
        return super.onInterceptTouchEvent(event);
    }

    @Override
    public void onLongClick(View view, final Conversation conversation) {


        showPopupWindow(context, view, conversation);

//        ConfirmDialog confirmDialog = new ConfirmDialog(context, "提醒", "删除该会话？", true);
//        confirmDialog.show();
//        confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//            @Override
//            public void confirm() {
//                conversationService.deleteConversation(conversation);
//                // refreshVideoItem();
//            }
//        });

    }

    @Override
    public void onConversationAdd(Conversation conversation) {
        int toPosition = getToPosition();
        conversationList.add(toPosition, conversation);
        if (conversationListAdapter.isShowFilterData()) {
            conversationListAdapter.filter();
        } else {
            conversationListAdapter.notifyItemInserted(toPosition);
        }
        scrollToPosition(toPosition);
    }

    @Override
    public void onConversationRemove(Conversation conversation) {
        if (!conversationList.contains(conversation)) {
            return;
        }
        int index = conversationList.indexOf(conversation);
        conversationList.remove(index);

        if (conversationListAdapter.isShowFilterData()) {
            conversationListAdapter.notifyItemRemovedOnShowFilterData(conversation);
        } else {
            conversationListAdapter.notifyItemRemoved(index);
            conversationListAdapter.notifyItemRangeChanged(index, conversationList.size() - index);
        }

    }

    @Override
    public void onConversationChange(Conversation conversation) {
        //当显示过滤数据的时候，
        if (conversationListAdapter.isShowFilterData()) {
            return;
        }
        int index = conversationList.indexOf(conversation);
        conversationListAdapter.notifyItemChanged(index);
//        if (conversationListAdapter.isShowFilterData()) {
//            conversationListAdapter.notifyItemChangedOnShowFilterData(conversation);
//        } else {
//            conversationListAdapter.notifyItemChanged(index);
//        }
    }

    @Override
    public void onMessageChange(Conversation conversation) {
        if (conversationListAdapter.isShowFilterData()) {//当显示过滤数据的时候（在搜索消息的时候），不在会话列表的item中显示新收到的消息
            return;
        }
        if (conversation.isTop()) {//置顶项，无须移动位置，只需要刷新消息
            conversationListAdapter.notifyItemChanged(conversationList.indexOf(conversation), ConversationListAdapter.REFRESH_MESSAGE);
        } else {
            int toPosition = getToPosition();
            changePosition(conversation, toPosition, ConversationListAdapter.REFRESH_MESSAGE);

        }
    }

    /**
     * 遍历集合，获取第一个非置顶的index
     *
     * @return
     */
    private int getToPosition() {
        int toPosition = 0;
        for (int i = 0; i < conversationList.size(); i++) {
            if (!conversationList.get(i).isTop()) {
                toPosition = i;
                break;
            }
        }
        return toPosition;
    }

    /**
     * 置顶
     *
     * @param conversation
     */
    private void toTop(Conversation conversation, int refreshFlag) {
        changePosition(conversation, 0, refreshFlag);
    }

    private void changePosition(Conversation conversation, int toPosition, int refreshFlag) {
        int index = conversationList.indexOf(conversation);
        if (index != -1) {//移动item的位置到顶部
            if (index != toPosition) {
                conversationList.remove(index);
                conversationList.add(toPosition, conversation);
                conversationListAdapter.notifyItemMoved(index, toPosition);
                if (toPosition == 0) {
                    scrollToPosition(0);
                }
            }
            conversationListAdapter.notifyItemChanged(toPosition, refreshFlag);
        }
    }

    @Override
    public void onUserInfoChange(Conversation conversation) {

        if (conversationListAdapter.isShowFilterData()) {
            conversationListAdapter.notifyItemChangedOnShowFilterData(conversation, ConversationListAdapter.REFRESH_USER_INFO);
        } else {
            int index = conversationList.indexOf(conversation);
            if (index != -1) {//用户信息改变，不用移动item 的位置，只刷新用户信息
                conversationListAdapter.notifyItemChanged(index, ConversationListAdapter.REFRESH_USER_INFO);
            }
        }
    }

    public class MyItemTouchHelperCallBack extends ItemTouchHelper.Callback {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFlags = ItemTouchHelper.ACTION_STATE_IDLE;
            int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            Log.d(TAG, "onSwiped: 滑动删除，，，，");
            int position = viewHolder.getAdapterPosition();
            final Conversation conversation = conversationList.get(position);
            conversationService.deleteConversation(conversation);


        }
    }

    private void showPopupWindow(final Context context, @NonNull View anchorView, Conversation targetConversation) {
        String TO_TOP = "置顶";
        String DELETE = "删除";
        String CANCEL_TOP = "取消置顶";
        List<String> popWindowItems = new ArrayList<>();
        if (targetConversation.isTop()) {
            popWindowItems.add(CANCEL_TOP);
        } else {
            popWindowItems.add(TO_TOP);
        }
        popWindowItems.add(DELETE);
        final ListPopupWindow popupWindow = new ListPopupWindow(context);
        popupWindow.setAdapter(new MenuArrayAdapter(context, R.layout.right_menu_item, R.id.tv_dialog_item, popWindowItems));
        popupWindow.setWidth(Utils.dpToPx(100, context));//也可以设置具体的值。容易出错的地方
        popupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
        popupWindow.setAnchorView(anchorView);//设置参照控件
        if (touchEvent != null) {
            popupWindow.setHorizontalOffset((int) touchEvent.getRawX());//相对锚点偏移值，正值表示向右偏移
        }
        // popupWindow.setVerticalOffset((int) touchEvent.getRawY());//相对锚点偏移值，正值表示向下偏移
        //popupWindow.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.popup_window_selector));
        popupWindow.setDropDownGravity(Gravity.START);//设置对齐方式。Gravity.START表示与参照控件左侧对齐，Gravity.END表示与参照控件右侧对齐。容易出错的地方
        popupWindow.setModal(true);//模态框，设置为true响应物理键
        popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                String s = popWindowItems.get(position);
                if (TextUtils.equals(s, TO_TOP)) {
                    targetConversation.updatePosition(0);
                    toTop(targetConversation, ConversationListAdapter.REFRESH_BACKGROUND);
                    //遍历，获取其他置顶项，修改他们的位置数据
                    for (int i = 1; i < conversationList.size(); i++) {
                        Conversation conversation1 = conversationList.get(i);
                        if (conversation1.isTop()) {
                            conversation1.updatePosition(i);
                        } else {
                            break;
                        }
                    }
                } else if (TextUtils.equals(s, DELETE)) {
                    conversationService.deleteConversation(targetConversation);
                } else if (TextUtils.equals(s, CANCEL_TOP)) {
                    targetConversation.updatePosition(ConversationData.DEFAULT_POSITION);//取消置顶，设置回默认的位置即可，
                    int index = conversationList.indexOf(targetConversation);
                    conversationListAdapter.notifyItemChanged(index, ConversationListAdapter.REFRESH_BACKGROUND);
                    int lastTopConversationIndex = index;
                    for (int i = index + 1; i < conversationList.size(); i++) {
                        Conversation conversation1 = conversationList.get(i);
                        if (conversation1.isTop()) {
                            conversation1.updatePosition(i - 1);
                            lastTopConversationIndex = i;
                        } else {
                            break;
                        }
                    }
                    if (index != lastTopConversationIndex) {//如果目标项并非最后一个置顶项，需要把目标项移动到置顶的尾部
                        conversationList.remove(targetConversation);
                        conversationList.add(lastTopConversationIndex, targetConversation);
                        conversationListAdapter.notifyItemMoved(index, lastTopConversationIndex);
                    }
                }
            }
        });
        popupWindow.show();
    }

}
